// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <melon/benchmark.h>
#include <melon/init/init.h>
#include <pollux/benchmarks/ExpressionBenchmarkBuilder.h>
#include <pollux/functions/macros.h>
#include <pollux/functions/registerer.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>

using namespace kumo::pollux;
using namespace kumo::pollux::exec;

namespace {

template <typename TExec>
struct udf_contains {
  POLLUX_DEFINE_FUNCTION_TYPES(TExec);

  MELON_ALWAYS_INLINE bool call(
      bool& out,
      const arg_type<Array<int32_t>>& array,
      const arg_type<int32_t>& key) {
    if (array.may_have_nulls()) {
      auto nullFound = false;
      for (const auto& item : array) {
        if (item.has_value()) {
          if (*item == key) {
            out = true;
            return true;
          }
          continue;
        }
        nullFound = true;
      }

      if (!nullFound) {
        out = false;
        return true;
      }
      return false;
    }

    // Not nulls path
    for (const auto& item : array) {
      if (*item == key) {
        out = true;
        return true;
      }
    }
    out = false;
    return true;
  }
};

} // namespace

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};
  memory::MemoryManager::initialize({});
  functions::prestosql::registerArrayFunctions();

  register_function<
      udf_contains,
      bool,
      kumo::pollux::Array<int32_t>,
      int32_t>({"contains_alt"});

  ExpressionBenchmarkBuilder benchmarkBuilder;
  auto inputType = ROW({"c0", "c1"}, {ARRAY(INTEGER()), INTEGER()});

  benchmarkBuilder.addBenchmarkSet("contains_benchmark", inputType)
      .addExpression("vector", "contains(c0,  c1)")
      .addExpression("simple", "contains_alt(c0, c1)");

  benchmarkBuilder.addBenchmarkSet("contains_benchmark_with_nulls", inputType)
      .withFuzzerOptions({.vectorSize = 1000, .nullRatio = 0})
      .addExpression("vector", "contains(c0,  c1)")
      .addExpression("simple", "contains_alt(c0, c1)");

  benchmarkBuilder.registerBenchmarks();
  // Make sure all expressions within benchmarkSets have the same results.
  benchmarkBuilder.testBenchmarks();
  melon::runBenchmarks();
  return 0;
}
